package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Recruit;
import cn.edu.seu.herald.informationplatform.dao.database.RecruitDao;

public class LeagueRecruitRequired implements Filter {

	public static final String RECRUIT_BEAN_NAME = "recruitBean";

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		String leagueIdParam = httpRequest.getParameter(
				LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
		
		try {
			int leagueId = Integer.valueOf(leagueIdParam);
			RecruitDao recruitAccess = RecruitDao.getDao();
			Recruit recruit = recruitAccess.getRecruitById(leagueId);
			httpRequest.setAttribute(RECRUIT_BEAN_NAME, recruit);
		} catch (NumberFormatException e) {
			httpResponse.sendError(400);
			return;
		} catch (SQLException e) {
			httpResponse.sendError(500);
			return;
		}
		
		chain.doFilter(request, response);
	}

}
